<template>
  <t-drawer
    :title="title"
    placement="right"
    :width="640"
    :visible="visible"
    :confirmLoading="loading"
    @close="
      () => {
        $emit('cancel');
      }
    "
  >
    <a-spin :spinning="loading">
      <a-alert
        message="新建完菜单后请去【平台管理】->【系统权限】->【岗位角色权限】处给对应角色进行授权"
        banner
        style="margin-bottom: 10px;"
      />
      <a-form :form="form">
        <a-form-item
          v-if="title == '新建'"
          label="来源"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-select v-model="menuAddType" @change="handleSource($event)">
            <a-select-option value="1">
              新增
            </a-select-option>
            <a-select-option value="2">
              引入
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          v-if="menuAddType == '2'"
          label="所有菜单"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-select
            v-model="menuSelect"
            @change="handleSlect($event)"
            showSearch
            placeholder="请选择菜单"
          >
            <a-select-option
              :value="item.menuCode"
              v-for="(item, index) in menuSource"
              :key="index"
            >
              {{ item.menuName }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          label="上级菜单"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <depart-popup
            title="菜单管理"
            searchPlaceholder="请输入菜单名称"
            placeholder="上级菜单"
            url="/system/menu/getAllTreeSysMenu"
            getDetailUrl="/system/menu/getListSysMenuById"
            labelName="menuName"
            valueName="id"
            detailId="id"
            v-decorator="[
              'pid',
              { rules: [{ required: true, message: '请选择上级菜单！' }] },
            ]"
          ></depart-popup>
        </a-form-item>
        <a-form-item
          label="菜单类型"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-select
            placeholder="菜单类型"
            v-decorator="[
              'menuType',
              { rules: [{ required: true, message: '请选择菜单类型！' }] },
            ]"
            @change="handleChange"
          >
            <a-select-option
              v-for="(item, index) in resourceType"
              :key="index"
              :value="item.type"
            >
              {{ item.text }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="菜单名称"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-input
            v-decorator="[
              'menuName',
              { rules: [{ required: true, message: '请输入菜单名称！' }] },
            ]"
            placeholder="菜单名称"
          />
        </a-form-item>
        <a-form-item
          label="菜单编码"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-input
            :disabled="type == 2"
            v-decorator="[
              'menuCode',
              {
                rules: [
                  {
                    required: type == 2 ? false : true,
                    message: '请输入菜单编码',
                  },
                ],
              },
            ]"
            placeholder="菜单编码"
          />
        </a-form-item>

        <a-form-item
          :label="$ct('menuPath', '菜单路径')"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-input
            v-decorator="[
              'menuUrl',
              { rules: [{ required: true, message: '请输入菜单路径' }] },
            ]"
            placeholder="菜单路径"
          />
        </a-form-item>
        <template
          v-if="
            resourceTypeValue !== 'button' &&
              resourceTypeValue != 'urlInsidePage'
          "
        >
          <a-form-item
            :label="$ct('frontEndComponents', '前端组件')"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
          >
            <a-select v-model="componentValue" @change="componentChange">
              <a-select-option value="TabsView">
                {{ $ct("outerLayout", "外层布局(TabsView)") }}
              </a-select-option>
              <a-select-option value="PageView">
                {{ $ct("pageLayout", "页面布局(PageView)") }}
              </a-select-option>
              <a-select-option value="RouteView">
                {{ $ct("emptyLayout", "空布局(RouteView)") }}
              </a-select-option>
              <a-select-option value="">
                {{ $ct("pageAddress", "页面地址") }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </template>
        <a-form-item
          label="动态路由"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          v-if="!componentValue"
        >
          <a-switch
            v-model="autoRouter"
            v-decorator="[
              'autoRouter',
              { valuePropName: 'checked' },
              { rules: [{ required: false, message: '' }] },
            ]"
          />
          <span style="color: red;">（仅限开发者使用，非开发人员慎用！）</span>
        </a-form-item>
        <a-form-item
          v-show="isUrl"
          :label="$ct('pageAddress', '页面地址')"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-input
            placeholder="具体路径"
            v-decorator="[
              'menuAssembly',
              { rules: [{ required: isUrl, message: '请输入具体路径！' }] },
            ]"
          />
        </a-form-item>
        <a-form-item
          :label="$ct('resourceSorting', '资源排序')"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-input-number
            id="inputNumber"
            style="width: 100%;"
            :min="0"
            placeholder="资源排序"
            v-decorator="[
              'menuSort',
              { rules: [{ required: true, message: '必填' }] },
            ]"
          />
        </a-form-item>
        <a-form-item
          :label="$ct('resourceIcon', '资源图标')"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <icon-font-picker
            placeholder="资源图标"
            v-decorator="['iconCls', { initialValue: '' }]"
            @change="handleIconChoose"
          ></icon-font-picker>
        </a-form-item>
        <a-form-item
          v-if="resourceTypeValue === 'APP'"
          :label="$ct('iconBackgroundColor', '图标背景颜色')"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <color-picker
            v-decorator="['iconClsColour', { initialValue: iconClsColour }]"
            @change="changeClsColour"
          />
        </a-form-item>
        <!-- <a-form-item :label="是否缓存该路由" :labelCol="labelCol" :wrapperCol="wrapperCol">
					<a-radio-group name="radioGroup" v-decorator="['keepAlive', {initialValue: false}]">
						<a-radio :value="true">
							是
						</a-radio>
						<a-radio :value="false">
							否
						</a-radio>
					</a-radio-group>
				</a-form-item> -->
        <a-form-item
          :label="$ct('state', '状态')"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <t-dict-select-tag
            type="select"
            dictCode="MenuStatus"
            :allowClear="false"
            placeholder="状态"
            v-decorator="[
              'menuStatus',
              {
                initialValue: 'MenuStatus.01',
                rules: [{ required: true, message: '请选择此处！' }],
              },
            ]"
          />
        </a-form-item>
        <a-form-item
          :label="$ct('configDescription', '配置说明')"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <div
            style="color: gray;font-size: 12px;line-height: 18px;padding-bottom:20px;"
          >
            <p>
              菜单路径配置说明： 1.
              子菜单页面（即具体的页面），URL配置规则：按照功能模块定义的关键根路径即可，不能重复。<br />
              2. 普通的子菜单（即有下级的菜单），URL和前端组件配置保持一致即可
            </p>
            <p>
              前端组件配置说明: 1.
              子菜单页面（即具体的页面）配置相对于src/views目录的路径，<br />
              2. 普通的子菜单（即有下级的菜单）配置固定
              前端组件TabsView(最外层菜单tab)/PageView(页面视图)/RouteView(路由视图)
            </p>
          </div>
        </a-form-item>
        <a-form-item class="hiddenItem">
          <a-input v-decorator="['uuid']" disabled type="hidden" />
        </a-form-item>
      </a-form>
    </a-spin>
    <div
      :style="{
        background: 'rgba(255,255,255,1)',
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        textAlign: 'right',
        zIndex: 1,
      }"
    >
      <a-button
        :style="{ marginRight: '8px' }"
        @click="
          () => {
            $emit('cancel');
          }
        "
      >
        取消
      </a-button>
      <a-button
        type="primary"
        @click="
          () => {
            $emit('ok');
          }
        "
      >
        确认
      </a-button>
    </div>
  </t-drawer>
</template>

<script>
import pick from "lodash.pick";
import TreeSelect from "@/components/TopVUI/custom/TreeSelect";
import colorPicker from "@/components/TopVUI/color/colorPicker";
import iconFontPicker from "@/components/TopVUI/font/iconFontPicker";
import { DepartPopup, TDictSelectTag } from "@/components";
import { getMenuSelect } from "@/api/common";

const fields = [
  "uuid",
  "pid",
  "menuName",
  "menuType",
  "menuCode",
  "menuUrl",
  "menuAssembly",
  "menuSort",
  "iconCls",
  "iconClsColour",
  "menuStatus",
  "autoRouter",
];
export default {
  props: {
    visible: {
      type: Boolean,
      default: () => false,
    },
    loading: {
      type: Boolean,
      default: () => false,
    },
    model: {
      type: Object,
      default: () => null,
    },
    type: {
      type: String,
    },
  },
  components: {
    TreeSelect,
    iconFontPicker,
    colorPicker,
    DepartPopup,
    TDictSelectTag,
  },
  data() {
    return {
      title: "",
      resourceType: [
        {
          text: "菜单",
          type: "menu",
        },
        {
          text: "链接-新窗口",
          type: "urlNewWindows",
        },
        {
          text: "APP菜单",
          type: "APP",
        },
        // {
        // 	text: '链接-外链',
        // 	type: 'outerChain'
        // },
        {
          text: "链接-内页",
          type: "urlInsidePage",
        },
      ],
      treeData: [],
      icon: [],
      status: [
        {
          text: "启用",
          value: 1,
        },
        {
          text: "禁用",
          value: 0,
        },
      ],
      labelCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 5,
        },
      },
      wrapperCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 18,
        },
      },
      form: this.$form.createForm(this),
      levelId: 1,
      pid: 1,
      url: {
        fathersUrl: "/system/menu/getListByLevelId",
        expandUrl: "/system/menu/getListByPid",
      },
      parameter: {
        father: {
          levelId: 1,
        },
        children: {},
      },
      resourceTypeValue: "",
      iconClsColour: "",
      componentValue: "TabsView",
      isUrl: false,
      autoRouter: false,
      //来源
      menuAddType: "1",
      menuSelect: undefined,
      menuSource: [],
    };
  },
  mounted: function() {},
  created() {
    // 防止表单未注册
    fields.forEach((v) => this.form.getFieldDecorator(v));
    // 当 model 发生改变时，为表单设置值
    this.$watch("model", () => {
      this.model && this.form.setFieldsValue(pick(this.model, fields));
    });
  },
  methods: {
    getMenuData() {
      getMenuSelect()
        .then((res) => {
          this.menuSource = res.data ?? [];
        })
        .catch((_) => {
          this.menuSource = [];
        });
    },

    handleSource(value) {
      if (value == "2") {
        this.getMenuData();
      }
    },
    handleSlect(value) {
      fields.forEach((v) => this.form.getFieldDecorator(v));
      let currentMenu = this.menuSource.find((v) => v.menuCode == value);
      this.form.setFieldsValue({
        menuName: currentMenu.menuName,
      });
      this.form.setFieldsValue({
        menuCode: currentMenu.menuCode,
      });
      this.form.setFieldsValue({
        menuType: currentMenu.menuType,
      });
      this.form.setFieldsValue({
        menuUrl: currentMenu.menuUrl,
      });
      this.form.setFieldsValue({
        menuAssembly: currentMenu.menuAssembly,
      });
      this.form.setFieldsValue({
        menuStatus: currentMenu.menuStatus,
      });
      this.form.setFieldsValue({
        iconCls: currentMenu.iconCls,
      });
      this.form.setFieldsValue({
        menuSort: currentMenu.menuSort,
      });
      this.form.setFieldsValue({
        autoRouter: currentMenu.autoRouter,
      });
      this.form.setFieldsValue({
        iconClsColour: currentMenu.iconClsColour,
      });
    },

    handleChange(value) {
      this.form.setFieldsValue({
        codeSetId: value,
      });
      this.resourceTypeValue = value;
    },
    add(m, data) {
      this.treeData = data ? data : [];
      this.pid = m ? m.id : "";
      this.form.setFieldsValue({
        menuAssembly: "TabsView",
      });
      this.componentValue = "TabsView";
      this.isUrl = false;
    },
    edit(m, data) {
      this.treeData = data;
      this.pid = m.pid;
      this.resourceTypeValue = m.resourceType;
      this.iconClsColour = m.iconClsColour;
      if (~["TabsView", "PageView", "RouteView"].indexOf(m.menuAssembly)) {
        this.componentValue = m.menuAssembly;
        this.isUrl = false;
      } else {
        this.componentValue = "";
        this.isUrl = true;
      }
    },
    handleIconChoose(value) {
      this.form.setFieldsValue({
        iconCls: value,
      });
    },
    changeClsColour(val) {
      this.form.setFieldsValue({
        iconClsColour: val,
      });
    },
    componentChange(val) {
      this.form.setFieldsValue({
        menuAssembly: val,
      });
      this.isUrl = !Boolean(val);
    },
  },
};
</script>

<style></style>
